<template>
  <el-dialog
    v-model="visible"
    width="65%"
    @close="handleClose"
    :show-close="false"
    :modal="false"
    style="background-color: rgba(15, 32, 54, 0.8)"
  >
    <div class="dialogBox">
      <div class="right">
        <div class="button-group">
          <el-button type="primary" @click="switchTable('基本信息')"
            >基本信息</el-button
          >
          <el-button type="primary" @click="switchTable('健康档案')"
            >健康档案</el-button
          >
        </div>
        <div class="card">
          <div
            v-if="activeTab === '基本信息'"
            style="
              display: flex;
              justify-content: space-around;
              margin-top: 24px;
              height: 500px;
            "
          >
            <el-descriptions
              title="设备"
              :column="1"
              style="margin-right: 230px"
            >
              <el-descriptions-item
                v-for="(value, key) in row"
                :key="key"
                :label="key"
              >
                {{ value }}
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions
              title="健康档案"
              :column="1"
              style="margin-top: -2px"
            >
              <el-descriptions-item
                v-for="(value, key) in health"
                :key="key"
                :label="key"
              >
                <span :style="getStatusStyle(value)">
                  {{ value ? "正常" : "异常" }}
                </span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="activeTab === '健康档案'">
            <el-row :gutter="24">
              <!-- 标题 -->
              <el-col :span="3">
                <span style="color: #4cfefe; font-size: 20px">{{
                  activeTab
                }}</span>
              </el-col>

              <!-- 搜索框和按钮 -->
              <el-col :span="7">
                <el-date-picker
                  style="width: 230px"
                  v-model="dateRange"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-value="[new Date(), new Date()]"
                  @change="handleDateChange"
                />
              </el-col>

              <el-col :span="7">
                <div style="display: flex; align-items: center">
                  <span
                    style="
                      margin-right: 10px;
                      white-space: nowrap;
                      color: #fff !important;
                    "
                    >档案ID:</span
                  >
                  <el-input
                    v-model="queryParams.heathCode"
                    style="flex: 1; height: 30px"
                    placeholder="请输入档案ID"
                    :suffix-icon="Search"
                  />
                </div>
              </el-col>

              <el-col :span="7">
                <el-button type="primary" @click="fetchHealthRecords"
                  >查询</el-button
                >
                <el-button @click="handleReset">重置</el-button>
                <el-dropdown placement="bottom" style="margin-left: 24px">
                  <el-button>筛选</el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleFilter(1)"
                        >健康</el-dropdown-item
                      >
                      <el-dropdown-item @click="handleFilter(0)"
                        >异常</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
            </el-row>
            <el-table class="custom-table" :data="currentTableData" :border>
              <el-table-column prop="heathCode" label="档案ID" />
              <el-table-column prop="robotCode" label="机器人编号" />
              <el-table-column prop="robotStatus" label="健康状态">
                <template #default="{ row }">
                  {{ robotStatus(row.robotStatus) }}
                </template>
              </el-table-column>
              <el-table-column prop="heathTime" label="检测时间">
                <template #default="{ row }">
                  {{ formatTime(row.heathTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="uploadTime" label="上传时间">
                <template #default="{ row }">
                  {{ formatTime(row.uploadTime) }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-model:current-page="queryParams.pageNo"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 20, 30, 50]"
              :background="background"
              layout="sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, nextTick, computed, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { RobotApi } from "@/api/map/robot";
import { Api } from "@/api/map/monitor";
import dayjs from "dayjs"; // 引入 dayjs
const visible = ref(false);
const input = ref("");
const row = ref({});
const activeTab = ref("基本信息"); // 新增状态变量
const currentPage = ref(4); // 当前页码
const pageSize = ref(100); // 每页显示的数量
const size = ref("default");
const background = ref(true);
const disabled = ref(false);
const rowid = ref();
const total = ref();
// 当前显示的表格数据
const currentTableData = ref([]);
const tableKey = ref(0);
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  heathCode: "",
  robotId: null,
  beginCreateTime: null,
  endCreateTime: null,
  robotStatus: null, //健康状态
  robotType: null, // 1: 智能盘点机器人, 2: 智能还书系统, 3: 智能导览机器人
});

// 计算属性，处理日期格式化
const dateRange = computed({
  get() {
    // 格式化日期
    return [
      queryParams.beginCreateTime
        ? dayjs(queryParams.beginCreateTime).format("YYYY-MM-DD")
        : null,
      queryParams.endCreateTime
        ? dayjs(queryParams.endCreateTime).format("YYYY-MM-DD")
        : null,
    ];
  },
  set(value) {
    // 设置日期时，直接使用 value 更新 queryParams
    queryParams.beginCreateTime = value[0]
      ? dayjs(value[0]).format("YYYY-MM-DD")
      : null;
    queryParams.endCreateTime = value[1]
      ? dayjs(value[1]).format("YYYY-MM-DD")
      : null;
  },
});
const robotStatus = (status) => {
  const STATUSES = [
    { robotStatus: 0, name: "异常" },
    { robotStatus: 1, name: "正常" },
  ];

  const matched = STATUSES.find((item) => item.robotStatus === status);
  return matched ? matched.name : "";
};
onMounted(() => {});
// 时间格式化函数
const formatTime = (timestamp) => {
  if (!timestamp) return ""; // 如果时间戳为空，返回空字符串
  return dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss"); // 自定义格式
};
// 获取健康档案数据
const fetchHealthRecords = async () => {
  // console.log(queryParams);
  queryParams.robotId = rowid.value;
  const res = await Api.getMonitorPage(queryParams);
  currentTableData.value = res.list;
  total.value = res.total;
  // console.log(res, "健康档案", rowid.value);
  // 在数据更新后，手动调整布局
  nextTick(() => {
    const table = document.querySelector(".el-table");
    if (table) {
      table.style.width = "800px"; // 确保表格宽度固定
    }
  });
};
// 根据状态返回样式对象
const getStatusStyle = (value) => {
  return {
    color: value ? "green" : "red",
  };
};
const health = ref({});
const getList = async () => {
  const res = await Api.getMonitorget(rowid.value);
  row.value = JSON.parse(res.configs);
  health.value = JSON.parse(res.healthStatus);
  //console.log(res.healthStatus, "基本信息", JSON.parse(res.configs));
};

// 打开弹框
const openDialog = (robot) => {
  visible.value = true;
  activeTab.value = "基本信息"; // 重置为基本信息
  rowid.value = robot.id;

  getList();
};
// 切换
const switchTable = async (table) => {
  activeTab.value = table;
  // 在 openDialog 中获取基本信息
  if (table === "基本信息") {
    if (rowid.value) {
      activeTab.value = "基本信息";
      getList();
    }
  }
  if (table === "健康档案") {
    queryParams.robotId = rowid.value;
    if (rowid.value) {
      activeTab.value = "健康档案";
      fetchHealthRecords();
    }
  }
};
// 关闭弹框
const handleClose = () => {
  visible.value = false;
};
// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  //getList();
  fetchHealthRecords();
};
// 处理当前页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNo = 1;
  queryParams.pageNo = val;
  //getList();
  fetchHealthRecords();
};
// 重置查询参数
const resetQueryParams = () => {
  queryParams.pageNo = 1;
  queryParams.pageSize = 10;
  queryParams.heathCode = "";
  queryParams.beginCreateTime = null;
  queryParams.endCreateTime = null;
  queryParams.robotStatus = null;
};
// 重置按钮点击事件
const handleReset = () => {
  resetQueryParams();
  fetchHealthRecords(); // 重新获取数据
};

// 筛选按钮点击事件
const handleFilter = (status) => {
  queryParams.robotStatus = status;
  fetchHealthRecords(); // 重新获取数据
};
// 暴露方法
defineExpose({ openDialog, switchTable });
</script>

<style lang="scss" scoped>
.dialogBox {
  .left {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
  }
  display: flex;
  justify-content: center;
}
/* 设置表格宽度和 box-sizing */
::v-deep .el-table {
  margin-top: 16px;
  background-color: transparent !important;
  border: 1px solid #627680 !important;
  width: 500px; /* 或者设置一个具体的宽度 */
  table-layout: fixed; /* 确保表格宽度固定，避免扩展 */
  box-sizing: border-box; /* 包括边框和内边距在内计算宽度 */
  margin-bottom: 20px;
  height: 350px;
  margin-left: 35px;
}
::v-deep .el-table__body {
  width: 500px !important;
}
::v-deep .el-table tr {
  color: #fff;
  height: 46px;
  white-space: nowrap;
  background-color: transparent !important;
}
::v-deep .custom-table .el-table__header th,
::v-deep .custom-table .el-table__body td {
  text-align: center;
  border: 1px solid #627680;
  background-color: transparent !important;
}
::v-deep .el-pagination__goto {
  color: #fff;
}
::v-deep .el-pagination__classi + fier {
  color: #fff;
}
// .card {
//   height: 650px;
//   width: 850px;
//   // background-color: rgba(20, 61, 81, 0.8);
//   // border: 1px solid rgba(20, 61, 81, 0.1);
//   color: #fff;
//   padding: 20px;
//   box-sizing: border-box;
// }
.button-group {
  margin-bottom: 20px;
}
::v-deep .el-descriptions__body {
  background: transparent !important;
  color: #fff !important;
}
/* 修改 label 颜色 */
::v-deep .el-descriptions__label {
  color: #49ffff !important;
}
/* 修改内容文字颜色 */
::v-deep .el-descriptions__content {
  color: #fff !important;
}
::v-deep .el-pagination__classifier {
  color: #fff !important;
}
::v-deep .el-descriptions__title {
  color: #49ffff;
  font-size: 24px;
}
::v-deep .chuanTitle .el-descriptions__title {
  color: #49ffff;
}
::v-deep .oneTitle .el-descriptions__title {
  color: #49ffff;
}
</style>
